import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login/index.vue'
import layout from '../views/layout/index.vue'
import home from '../views/layout/home/index.vue'
import question from '../views/layout/question/index.vue'
import movie from '../views/layout/movie/index.vue'
import user from '../views/layout/user/index.vue'
import { getToken, removeToken } from '../utils/token'
import { Toast } from 'vant'
import { getUserInfo } from '../api/user'
import store from '@/store'
import edit from '../views/layout/edit'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/',
    name: 'layout',
    component: layout,
    children: [
      {
        path: 'home',
        name: 'home',
        component: home
      },
      {
        path: 'question',
        name: 'question',
        component: question
      },
      {
        path: 'movie',
        name: 'movie',
        component: movie
      },
      {
        path: 'user',
        name: 'user',
        component: user,
        meta: {
          needLogin: true
        }
      },
      {
        path: 'edit',
        name: 'edit',
        component: edit,
        meta: {
          needLogin: true,
          hideTabbar: true
        }
      }
    ]
  }
]
// 吞掉 没有处理的 promise的错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 执行之后 阻断后续代码
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin !== true) {
    return next()
  }
  if (store.state.userInfo.name !== undefined) {
    return next()
  }
  const tokenObj = getToken()
  if (tokenObj === null) {
    Toast.fail('温馨提示：请先登录')
    return next({ path: '/login', query: { redirect: to.path } })
  }
  getUserInfo()
    .then(res => {
      store.commit('setUserInfo', res.data.data)
      next()
    })
    .catch(eerRes => {
      if (eerRes.response.status === 401 || eerRes.response.status === 400) {
        removeToken()
        Toast.fail('温馨提示：请先登录')
        next({ path: '/login', query: { redirect: to.path } })
      }
    })
})
export default router
